﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class DamageReceiverCylinderColliders : DamageReceiverCollider {
    #region Fields

    public Transform[] A;
    public Transform[] B;

    public float[] radius;

    #endregion Fields

    #region Methods

    void OnStart() {
        init();
    }

    public override void CheckInsideColliderRay() {

        for(uint i = 0; i < radius.Length; i++) {
            Collider[] s1 = Physics.OverlapSphere(A[i].position, radius[i], layersToHit.value);
            Collider[] s2 = Physics.OverlapSphere(B[i].position, radius[i], layersToHit.value);

            AddColliers(s1);
            AddColliers(s2);
        }
    }


    //public Transform testDummy;
    public override bool PointInsideCollider(Vector3 aPoint) {
        aPoint.y = 0;
        bool isInCollider = false;
        for(int i = 0; i < A.Length; i++) {
            Vector3 APos = A[i].position.SetY(0);
            Vector3 BPos = B[i].position.SetY(0);
            Vector3 projectionOnAB = Vector3.Project(aPoint - APos, BPos - APos) + APos;

            float ABSqrMagnitude = (APos - BPos).sqrMagnitude;
            float sqrRadius = radius[i] * radius[i];

            bool flag = (aPoint - APos).sqrMagnitude <= sqrRadius ||
                        (aPoint - BPos).sqrMagnitude <= sqrRadius ||

                        (projectionOnAB - APos).sqrMagnitude <= ABSqrMagnitude &&
                        (projectionOnAB - BPos).sqrMagnitude <= ABSqrMagnitude &&
                        (aPoint - projectionOnAB).sqrMagnitude <= radius[i] * radius[i];

            if(flag) {
                isInCollider = true;
                break;
            }
        }
        return isInCollider;
    }

    void OnDrawGizmos() {
        if(DamageReceiverCollider.IsDrawColliderWire == false) {
            return;
        }
        if(enabled) {
            //Gizmos.color = Color.red;
            //Gizmos.DrawLine(A.position, B.position);

            Gizmos.color = Color.green;
            ////Gizmos.DrawLine(testDummy.position, Vector3.Project(testDummy.position - A.position, B.position - A.position) + A.position);
            for(int i = 0; i < A.Length; i++) {
                Gizmos.DrawWireSphere(A[i].position, radius[i]);
                Gizmos.DrawWireSphere(B[i].position, radius[i]);
                Gizmos.DrawLine(A[i].position, B[i].position);
            }
        }
    }

    #endregion Methods
}